<template>
    <!-- 图层管理 -->
    <div class="coverage" id="coverage">
        <div class="coverageTitle" @mousedown="mousedown" @mouseup="mouseup" @mouseout="mouseup">
            <div class="coverageTitleName">
                <img class="btnsImages" src="@/assets/image/btns/layer.png" alt="" />
                图层
            </div>
            <i class="el-icon-close closeIcon" title="关闭" @click="setCoverage"></i>
        </div>
        <!-- <div class="coverageTitle" @dragover="dragstart" @mousedown="mousedowns">
            <div class="coverageTitleName">
                <img class="btnsImages" src="@/assets/image/btns/layer.png" alt="" />
                图层
            </div>
            <i class="el-icon-close closeIcon" title="关闭" @click="setCoverage"></i>
        </div> -->
        <div class="toolBox">
            <div class="toolBtn">
                <i class="fa fa-folder-open-o" title="打开文件" @click="centerDialogVisible = true"></i>
                <!-- <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="uploadKML" accept=".kml">
                    <i class="fa fa-folder-open-o" title="打开文件"></i>
                </el-upload> -->
            </div>
            <div class="toolBtn">
                <!-- <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="uploadTiff" accept=".tif,.tiff">
                    <i class="fa fa-photo" title="打开模型"></i>
                </el-upload> -->
                <i class="fa fa-photo" title="打开模型" @click="zxyortif = true"></i>
            </div>
            <div class="toolBtn">
                <i class="fa fa-save" title="保存文档" @click="exportKML"></i>
            </div>
            <div class="halfSeparate"></div>
            <div class="toolBtn">
                <i class="fa fa-unlock" title="可编辑"></i>
                <!-- <i class="fa fa-lock" title="不可编辑"></i> -->
            </div>
        </div>
        <div class="treeBox">
            <div class="treeBoxDiv" @click="$store.commit('setContextMenu', false)">
                <el-scrollbar wrap-class="scrollbar-wrapper">
                    <!-- :render-content="renderContent" -->
                    <el-tree
                        ref="treeList"
                        :data="treeData"
                        :key="treeKey"
                        show-checkbox
                        node-key="id"
                        class="treeList"
                        highlight-current
                        :default-expand-all="isExpand"
                        :expand-on-click-node="false"
                        :props="$globalData.treeProps"
                        :default-expanded-keys="[1]"
                        @check-change="checkChange"
                        @node-contextmenu="nodeContextmenu"
                        @node-click="nodeClick"
                        @node-expand="closeContextmenu"
                        @node-collapse="closeContextmenu"
                        @check="checks"
                    >
                        <span class="custom-tree-node" slot-scope="{ data }">
                            <div v-if="data.type == 'folder'">
                                <i class="fa fa-lock treeNodeIcons" title="已锁定" v-if="data.isLocked == '1'"></i>
                                <span>{{ data.name }}</span>
                            </div>
                            <div v-else>
                                <!-- 图标点 -->
                                <i class="fa fa-map-pin treeNodeIcons" v-if="data.type == 'billboard'"></i>
                                <!-- 长方体 -->
                                <i class="fa fa-cube treeNodeIcons" v-if="data.type == 'box'"></i>
                                <!-- 线或曲线 -->
                                <img src="../../../assets/image/btns/xian.png" class="treeNodeIcons faImage" alt="" v-if="data.type == 'curve' || data.type == 'polyline'" />
                                <!-- <i class="fa fa-reorder treeNodeIcons" style="transform: rotate(90deg);" v-if="data.type == 'curve' || data.type == 'polyline'"></i> -->
                                <!-- 圆 -->
                                <i class="fa fa-circle-o treeNodeIcons" v-if="data.type == 'circle'"></i>
                                <!-- 矩形 -->
                                <i class="fa fa-square-o treeNodeIcons" v-if="data.type == 'rectangle'"></i>
                                <!-- 面 -->
                                <i class="fa fa-connectdevelop treeNodeIcons" v-if="data.type == 'polygon'"></i>
                                <!-- 椭圆柱体 -->
                                <i class="fa fa-database treeNodeIcons" v-if="data.type == 'ellipse'"></i>
                                <span>{{ data.name }}</span>
                            </div>
                        </span>
                    </el-tree>
                </el-scrollbar>
            </div>
        </div>
        <!-- 上传进度条 -->
        <div class="uploadProgress" v-if="percentageShow">
            <el-progress type="circle" v-if="percentageNum < 100" :percentage="percentageNum"></el-progress>
            <el-progress type="circle" v-else :percentage="100" status="success"></el-progress>
            <div class="uploadProgressTip" v-if="percentageNum <= 50">文件上传中，请稍后....</div>
            <div class="uploadProgressTip" v-if="percentageNum <= 85 && percentageNum > 50">文件解析中，请稍后....</div>
            <div class="uploadProgressTip" v-if="percentageNum < 100 && percentageNum > 85">文件储存中，请稍后....</div>
            <!-- <div class="uploadProgressTip" v-else>文件上传成功</div> -->
        </div>
        <!-- // 上传kml弹窗 -->
        <el-dialog title="上传kml" :visible.sync="centerDialogVisible" width="30%" center :modal="false" custom-class="uploadKMLBox">
            <div class="uploadKMLBoxCont">
                <div>
                    <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="uploadKML" accept=".kml">
                        <!-- <el-image class="uploadImages" :src="require('@/assets/kml.png')" fit="cover"></el-image> -->
                        <i class="el-icon-document uploadIcon"></i>
                        <br />
                        <el-button size="small" type="primary">上传自有KML</el-button>
                    </el-upload>
                </div>
                <div>
                    <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="uploadTuXinKML" accept=".kml">
                        <!-- <el-image class="uploadImages" :src="require('@/assets/kml.png')" fit="cover"></el-image> -->
                        <i class="el-icon-document uploadIcon"></i>
                        <br />
                        <el-button size="small" type="primary">上传图新KML</el-button>
                    </el-upload>
                </div>
            </div>
        </el-dialog>
        <!-- // 上传zxy标准金字塔瓦片或者tif弹窗 -->
        <el-dialog title="上传标准金字塔瓦片或者TIF" :visible.sync="zxyortif" width="30%" center :modal="false" custom-class="uploadKMLBox">
            <div class="uploadKMLBoxCont">
                <div>
                    <!-- <el-upload class="avatar-uploader uploadfolder" action="#" :show-file-list="false" :http-request="uploadFolder">
                        <i class="fa fa-folder-open-o uploadIcon"></i>
                        <br />
                        <el-button size="small" type="primary">标准金字塔瓦片</el-button>
                    </el-upload> -->
                    <div class="uploadfloderBox">
                        <i class="fa fa-folder-open-o uploadIcon"></i>
                        <br />
                        <el-button size="small" type="primary">标准金字塔瓦片</el-button>
                        <form id="uploadSoundCodeFolderForm" style="opacity: 0;" method="post" enctype="multipart/form-data">
                            <input type="file" class="uploadfloderBoxInput" webkitdirectory allowdirs directory multiple @change="uploadFolder" />
                        </form>
                        <!-- <input type="file" class="uploadfloderBoxInput" @change="uploadFolder" /> -->
                    </div>
                    <!-- <input type="file" webkitdirectory allowdirs directory multiple @change="uploadFolder" /> -->
                </div>
                <div>
                    <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="uploadTiff" accept=".tif,.tiff">
                        <!-- <el-image class="uploadImages" :src="require('@/assets/kml.png')" fit="cover"></el-image> -->
                        <i class="fa fa-photo uploadIcon"></i>
                        <br />
                        <el-button size="small" type="primary">TIF</el-button>
                    </el-upload>
                </div>
            </div>
        </el-dialog>
        <div class="zxyuploadscheduletip" v-if="zxy.zxyuploadscheduletip">
            <div class="zxyuploadscheduletipCenter">
                <div class="">{{ zxy.tiptext }}</div>
                <div class="">当前上传第{{ zxy.current }}个文件，共{{ zxy.total }}个文件</div>
                <div class=""><i class="el-icon-loading"></i>{{ zxy.fileName }}</div>
            </div>
        </div>
    </div>
</template>
<script>
import { initTreeData } from './utils/coverage.config'
import { mousedown, mouseup } from '../utils/move.el'
import trees from './utils/treeHandle'
import editorware from '../utils/editorMiddleware'
import cMenu from '../contextMenu/utils/contextMenu'
import render from './utils/renderEngine'
import Bus from '@/utils/bus.js'
import { initMap, Mars3d } from '@/components/utils/initMap'
import { marker, plane, box, ellipse } from '@/utils/publicStyle'
import * as turf from '@turf/turf'
// var Tiff = require('tiff.js')
// var fs = require('fs')
import SparkMD5 from 'spark-md5'

export default {
    name: 'coverage',
    data() {
        return {
            treeData: [],
            isExpand: true,
            treeKey: new Date().getTime(),
            percentageNum: 0,
            percentageShow: false,
            loadingMask: '',
            // 当前选中的节点
            // currentNodeKey: ''
            // disX: 0,
            // disY: 0
            // 树菜单点击次数
            treeClickCount: 0,
            // 上传kml弹窗
            centerDialogVisible: false,
            zxyortif: false,
            zxy: {
                zxyuploadscheduletip: false,
                current: 1,
                total: 0,
                fileName: '',
                fileId: null,
                tiptext: '正在上传，请耐心等待...'
            }
            // maplevel: 0
        }
    },
    computed: {
        coverageIsShow() {
            return this.$store.state.coverage
        }
    },
    watch: {
        coverageIsShow(newData) {
            let el = document.getElementById('singleProperty')
            let coverage = document.getElementById('coverage')

            coverage.style.left = '10px'
            coverage.style.top = '48px'
        }
        // 'map.level'(newData) {
        //     console.log(newData, '新的地图层级')
        // }
    },
    mounted() {
        // Bus.$on( 'treeFresh', (e) => {
        //     if(e == true){
        //     }
        // })
        this.initTree()
        editorware.init()
        // setInterval(() => {
        // console.log(map)
        //     this.maplevel = map.level
        //     console.log(map.level, '新的地图层级')
        // }, 1000)
        // console.log(this.$loading())
        // console.log(this.addCoverageObj, '0')
        // this.$alert('这是一段内容', '标题名称', {
        //     confirmButtonText: '确定',
        //     callback: action => {
        //         this.$message({
        //             type: 'info',
        //             message: `action: ${action}`
        //         })
        //     }
        // })
    },
    methods: {
        exportKML() {
            // console.log(initMap.graphicLayer)
            // var strResult = toKML()
            if (initMap.graphicLayer.length === 0) {
                this.$alert('当前没有标注任何数据，无需保存！')
                return
            }
            // console.log(haoutil)
            let strResult = this.toKML()
            haoutil.file.downloadFile('我的标注.kml', strResult)
        },
        toKML() {
            let geojsonObject = initMap.graphicLayer.toGeoJSON()
            if (geojsonObject == null) {
                return null
            }

            geojsonObject = haoutil.system.clone(geojsonObject)

            let kml = kgUtil.toKml(geojsonObject, {
                name: '数字果园标绘数据',
                documentName: '数字果园标绘数据文件',
                documentDescription: '标绘数据 by http://szfarm.com',
                simplestyle: true
            })

            return kml
        },
        // 关闭图层对话框
        setCoverage() {
            this.$store.commit('setCoverage')
        },
        // 初始化树形菜单
        initTree() {
            initTreeData('tree', this).then(res => {
                this.treeData = res.data
                // console.log(res.data)
                // return
                // this.$refs.treeList.setCheckedKeys(res.defaultChecked)
                editorware.treeObj = this.$refs.treeList
                if (!editorware.drawingId) {
                    editorware.drawingId = res.data[0].id
                }

                setTimeout(() => {
                    // 设置默认选中第一个
                    this.$refs.treeList.setCurrentKey(res.data[0].id)
                    // 获取当前选中node
                    editorware.treeSelectData = this.$refs.treeList.getCurrentNode()
                    // console.log(this.$refs.treeList.getCurrentNode())
                    // this.$refs.treeList.expanded = true
                    this.isExpand = false
                    this.DynamicScaling()
                    // 设置选中辅助图层
                    // 獲取到輔助圖層對象
                    const auxiliaryLayer = this.treeData.filter(item => {
                        if (item.name == '辅助图层') {
                            return item
                        }
                    })
                    // 获取到辅助图层对象ID
                    const auxiliaryLayerId = auxiliaryLayer[0].id
                    editorware.treeObj.setChecked(auxiliaryLayerId, true, false)
                    // 选择辅助图层内部
                    auxiliaryLayer[0].children.forEach(v => {
                        editorware.treeObj.setChecked(v.id, true, false)
                    })
                }, 100)
            })
        },
        // 收起所有菜单
        DynamicScaling() {
            for (let j = 0; j < this.$refs.treeList.store._getAllNodes().length; j++) {
                this.$refs.treeList.store._getAllNodes()[j].expanded = this.isExpand
            }
        },
        checkChange(e, show, children) {
            trees.checkChange(e, show, children)
        },
        // 树菜单右键事件
        nodeContextmenu(event, data, node, el) {
            editorware.isFlyTo = true
            this.closeContextmenu()
            const commitData = {
                isShow: true,
                X: event.x,
                Y: event.y,
                type1: 'treeMenu',
                type2: '',
                time: new Date().getTime()
            }
            // console.log(node.data.editor)
            if (node.data.editor) {
                this.$store.state.nodeId = node.data.id
                if (node.data.type == 'folder' && node.data.name == '三维模型') {
                    // 三维模型的右键菜单
                    commitData.type2 = 'model3D'
                } else {
                    if (node.data.type == 'folder') {
                        // 文件夹的右键菜单
                        // 判断文件夹是否被锁定isLocked: 锁定状态 1是 0否
                        if (node.data.isLocked == 0) {
                            commitData.type2 = 'folder'
                        } else {
                            commitData.type2 = 'unlock'
                        }
                    } else {
                        // 添加对象的右键菜单
                        // if (node.data.type != 'tif') {
                        commitData.type1 = 'layerMenu'
                        commitData.type2 = 'layer'
                        // }
                    }
                }
                // 打开右键菜单
                setTimeout(() => {
                    this.$store.commit('setContextMenu', commitData)
                    if (node.data.type != 'folder' && node.parent.data.isLocked == 1) {
                        this.$store.commit('setContextMenu', { isShow: false })
                    }
                    // 设置为选中状态
                    this.$refs.treeList.setCurrentKey(node.data.id)
                    // 设置选中的node
                    editorware.treeSelectNode = node
                    // 设置当前右击node

                    if (node.data.type == 'folder') {
                        editorware.rightClickNode = node
                    } else {
                        let graphic = editorware.rightClickData
                        console.log(graphic)
                        if (graphic && graphic.type != 'tif' && graphic.type != 'tile') {
                            graphic.stopEditing()
                        }
                        editorware.rightClickData = ''
                        // if (node.data.type != 'tif') {
                        editorware.rightClickData = editorware.coverageMap.get(node.data.id)
                        // }
                    }
                })
            }
        },
        closeContextmenu() {
            // 关闭右键菜单
            this.$store.commit('setContextMenu', false)
        },
        // 点击复选框事件
        checks(node, da) {
            // console.log(node, da)
            // console.log(da)
            let data = {
                folderId: '', // 文件夹ID
                drawingId: '', // 标绘ID
                isShow: '1' // 是否显示 1是 0不是
            }
            if (node.type == 'folder') {
                data.folderId = node.id
                data.drawingId = ''
            } else {
                data.folderId = ''
                data.drawingId = node.id
            }
            // 判断已选中列表是否存在点击node的ID
            if (da.checkedKeys.includes(node.id)) {
                data.isShow = '1'
            } else {
                data.isShow = '0'
            }
            this.$request.get('/api/map/draw/modifyThePlotDisplay', data)
        },
        // 树菜单点击事件
        nodeClick(data, node, el) {
            this.closeContextmenu()
            //记录点击次数
            this.treeClickCount++
            //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
            if (this.treeClickCount > 2) {
                this.treeClickCount = 0
                return
            }
            setTimeout(() => {
                if (this.treeClickCount == 2) {
                    editorware.isFlyTo = true
                    if (node.data.type == 'folder') {
                        editorware.treeSelectData = node
                        editorware.drawingId = data.id
                    } else if (node.data.type != 'kml' && node.data.type != 'tif') {
                        let graphic = editorware.rightClickData
                        if (graphic && graphic.type != 'tif' && graphic.type != 'tile') {
                            graphic.stopEditing()
                        }
                        editorware.rightClickData = editorware.coverageMap.get(node.data.id)
                        cMenu.property()
                    } else if (node.data.type == 'tif') {
                        // tif双击改名
                        this.$prompt('请输入新名称', '重命名', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            cancelButtonClass: 'el-button--primary',
                            customClass: 'inputFolder'
                        }).then(({ value }) => {
                            if (value) {
                                let addData = {
                                    id: node.data.id,
                                    name: value,
                                    style: {
                                        name: value
                                    }
                                }
                                node.data.name = value
                                this.$request
                                    .get('/api/map/draw/modifyPlotDataById', {
                                        drawQueryString: JSON.stringify(addData)
                                    })
                                    .then(res => {
                                        if (res.code == 200) {
                                            this.$message.success('修改成功')
                                        }
                                    })
                            } else {
                                this.$alert('文件名称不能为空')
                            }
                        })
                    } else {
                        let graphic = editorware.rightClickData

                        if (graphic && graphic.type != 'tif' && graphic.type != 'tile') {
                            graphic.stopEditing()
                        }
                        this.$store.commit('setSingleProperty', false)
                    }
                } else {
                    switch (node.data.type) {
                        case 'folder':
                            editorware.treeSelectData = node
                            editorware.drawingId = data.id
                            break
                        case 'tif':
                            // tif单击改名
                            // 修改后，单击飞图
                            setTimeout(() => {
                                if (this.treeClickCount == 1) {
                                    let tif = editorware.coverageMap.get(node.data.id)
                                    // console.log(tif)
                                    map.flyToExtent({
                                        xmin: tif.xmin,
                                        xmax: tif.xmax,
                                        ymin: tif.ymin,
                                        ymax: tif.ymax,
                                        height: 2000
                                    })
                                }
                            }, 10)
                        case 'tile':
                            setTimeout(() => {
                                if (this.treeClickCount == 1) {
                                    let tile = editorware.coverageMap.get(node.data.id)
                                    let zb = tile.options.rectangle
                                    console.log(zb)
                                    map.flyToExtent({
                                        xmin: zb.xmin,
                                        xmax: zb.xmax,
                                        ymin: zb.ymin,
                                        ymax: zb.ymax,
                                        height: 2000
                                    })
                                }
                            }, 10)
                            break
                        default:
                            console.log(node.data)
                    }
                }
                setTimeout(() => {
                    this.treeClickCount = 0
                }, 10)
            }, 300)
        },
        fragmentUpload(index, file, pid, md5) {
            // 分片大小v
            // console.log('开始上传分片---------')
            let fragmentSize = 1024 * 1024 * 5 // 20MB
            let { fname, fext } = file.name.split('.') //获取文件的名字和拓展名
            let chunks = Math.ceil(file.size / fragmentSize)
            let star = index * fragmentSize //切片的起点
            if (star > file.size) {
                //判断起点是否已经超过文件的长度，超过说明已经
                return
            }
            // let progress = (index / chunks) * 100

            // if (progress >= 50 && progress < 85) {
            //     this.loadingMask.text = '文件储存中...'
            // } else if (progress >= 85) {
            //     this.loadingMask.text = '文件解析中...'
            // }
            // return
            let bool = file.slice(star, star + fragmentSize) //slice（分割起点，分割终点）是js切割文件的函数，
            let boolname = fname + index + fext

            let boolfile = new File([bool], boolname) //把分割后的快转成文件传输
            let fromData = new FormData() //定义集合方便后端接收
            fromData.append('chunk', index)
            fromData.append('size', file.size)
            fromData.append('chunks', chunks)
            fromData.append('md5', md5)
            fromData.append('type', 'tif')
            fromData.append('folderId', pid)
            fromData.append('file', boolfile)
            fromData.append('layerName', file.name)

            this.$request
                .uploading('/api/map/draw/uploadDrawingLayer', fromData)
                .then(res => {
                    console.log(res)
                    if (res.code == 200) {
                        // chunks
                        // index
                        // 计算进度条进度
                        this.percentageNum = Number((((index + 1) / chunks) * 100).toFixed(2))
                        // console.log('开始上传下一分片---------')
                        this.fragmentUpload(++index, file, pid, md5)
                    }
                })
                .catch(e => {
                    // console.log(e)
                    if (e.code == 201) {
                        // 上传成功
                        // console.log(e.data.accessPath)
                        // this.percentageNum = 100

                        render(e.data, true)

                        let node = this.$refs.treeList.getNode(e.data.folderId)
                        let addNode = {
                            name: e.data.name,
                            pid: e.data.folderId,
                            id: e.data.id,
                            type: e.data.type,
                            editor: true,
                            show: false
                        }
                        if (node) {
                            this.$refs.treeList.append(addNode, node)
                        }
                        setTimeout(() => {
                            this.percentageShow = false
                            // this.loadingMask.close()
                        }, 300)
                    } else {
                        if (index < chunks - 1) {
                            this.fragmentUpload(index, file)
                        } else {
                            this.$message.error('上传失败,请稍后再试...')
                            this.loadingMask.close()
                            this.percentageShow = false
                            this.percentageNum = 0
                        }
                    }
                })
        },
        getFileMd5(file, callBack) {
            let spark = new SparkMD5()
            let fileReader = new FileReader()
            fileReader.readAsArrayBuffer(file)
            fileReader.onload = function(e) {
                //每块交由sparkMD5进行计算
                spark.appendBinary(e.target.result)
                callBack(spark.end())
            }
        },
        // 上传金字塔瓦片
        uploadFolder(e) {
            let files = e.target.files
            // console.log(this.$refs.treeList.getCheckedKeys())
            // return
            // 当前所有文件的唯一id和当前上传文件的总数
            let dateTime = new Date().getTime()
            this.zxy.fileId = `${parseInt(Math.random() * 10000 + 1)}${dateTime}`
            this.zxy.total = files.length
            // 获取父级id
            let pids = this.treeData.filter(v => {
                if (v.name == '三维建模') {
                    return v
                }
            })
            this.zxy.fileName = files[0].webkitRelativePath
            let fileName = this.zxy.fileName.split('/')[0]
            setTimeout(() => {
                if (pids.length > 0) {
                    this.uploadzxy(files, 0, pids[0].id, fileName)
                }
            }, 300)
        },
        uploadzxy(files, i, pid, fileName) {
            // 打开文件上传提示框
            if (!this.zxy.zxyuploadscheduletip) {
                this.zxy.zxyuploadscheduletip = true
            }
            this.zxy.current = i + 1
            this.zxy.fileName = files[i].webkitRelativePath
            // 组合上传参数
            let fromData = new FormData()
            fromData.append('file', files[i]) // 文件流
            fromData.append('type', 'tile') // 文件类型
            fromData.append('folderId', pid) // 文件pid
            fromData.append('layerName', fileName) // 文件名称
            fromData.append('uuid', this.zxy.fileId) // 文件临时唯一id
            fromData.append('filePath', files[i].webkitRelativePath) // 文件相对路径
            fromData.append('current', this.zxy.current) // 文件当前进度
            fromData.append('total', this.zxy.total) // 文件总数量
            this.$request.uploading('/api/map/tile/uploadTileFolder', fromData).then(res => {
                // console.log(res, v)
                if (res.code == 200) {
                    // 判断是否为最后一张
                    if (i == this.zxy.total - 1) {
                        this.zxy.zxyuploadscheduletip = false
                        let data = res.data
                        // console.log(data)
                        this.$alert('上传成功', {
                            confirmButtonText: '确定',
                            callback: action => {
                                this.zxyortif = false
                                this.zxy.fileId = null
                                this.zxy.zxyuploadscheduletip = false
                                this.zxy.current = 1
                                this.zxy.total = 0
                                this.zxy.fileName = ''
                                let obj = document.querySelector('.uploadfloderBoxInput')
                                obj.value = null

                                // 上传成功立即加载到地图
                                render(data, true)

                                let node = this.$refs.treeList.getNode(data.folderId)
                                let addNode = {
                                    name: data.name,
                                    pid: data.folderId,
                                    id: data.id,
                                    type: data.type,
                                    editor: true,
                                    show: true
                                }
                                if (node) {
                                    this.$refs.treeList.append(addNode, node)
                                    setTimeout(() => {
                                        this.$refs.treeList.setChecked(data.id, true)
                                    }, 500)
                                }
                                // 飞图到坐标处
                                map.flyToExtent({ xmin: Number(data.xmin), xmax: Number(data.xmax), ymin: Number(data.ymin), ymax: Number(data.ymax), height: 2000 })
                            }
                        })
                    } else {
                        this.uploadzxy(files, this.zxy.current, pid, fileName)
                    }
                } else {
                    // this.tiptext = '上传中断，请稍后再试'
                    this.$alert('上传中断，请稍后再试', {
                        confirmButtonText: '确定',
                        callback: action => {
                            this.zxyortif = false
                            this.zxy.fileId = null
                            this.zxy.zxyuploadscheduletip = false
                            this.zxy.current = 1
                            this.zxy.total = 0
                            this.zxy.fileName = ''
                            let obj = document.querySelector('.uploadfloderBoxInput')
                            obj.value = null
                        }
                    })
                }
            })
        },
        // 上传TIFF文件
        uploadTiff(e) {
            const file = e.file
            if (file.name.includes('.tif') || file.name.includes('.TIF')) {
                if (file.size <= 1024 * 1024 * 1024) {
                    // 验证文件大小不能超过1GB
                    let pid = ''
                    this.treeData.forEach(v => {
                        if (v.name == '三维建模') {
                            pid = v.id
                        }
                    })
                    setTimeout(() => {
                        this.percentageNum = 0
                        this.percentageShow = true
                        this.getFileMd5(file, res => {
                            this.fragmentUpload(0, file, pid, res)
                        })
                        // this.loadingMask = this.$loading({
                        //     text: '文件上传中...',
                        //     background: 'rgba(0,0,0,0.6)',
                        //     customClass: 'loadingMaskClass'
                        // })
                    }, 300)
                } else {
                    this.$alert('文件不能超过500MB')
                }
            } else {
                this.$alert('文件格式错误')
            }
        },
        // 上传KML文件
        uploadKML(e) {
            const file = e.file
            if (!file.name.includes('.kml')) {
                this.$alert('文件格式错误')
            } else {
                let baseId = sessionStorage.getItem('baseId')
                let pid = editorware.drawingId
                let formData = new FormData()
                formData.append('kmlFile', file)
                formData.append('saveId', pid)
                formData.append('baseId', baseId)
                this.$request.uploading('/api/map/draw/analyticKml', formData).then(res => {
                    if (res.code == 200) {
                        // console.log(res)
                        let data = res.data
                        // 文件夹处理
                        if (data.folderData && data.folderData.length > 0) {
                            data.folderData.forEach(v => {
                                let addData = {
                                    name: v.folderName,
                                    pid: v.parentFolder,
                                    id: v.id,
                                    type: 'folder',
                                    isLocked: v.isLocked,
                                    editor: v.isEditor ? true : false,
                                    show: v.isShow ? true : false,
                                    children: []
                                }
                                let node = this.$refs.treeList.getNode(v.parentFolder)
                                this.$refs.treeList.append(addData, node)
                            })
                        }
                        // 数据处理
                        if (data.drawData && data.drawData.length > 0) {
                            data.drawData.forEach(v => {
                                let addNode = {
                                    name: v.name,
                                    pid: v.folderId,
                                    id: v.id,
                                    type: v.type,
                                    editor: true,
                                    show: v.isShow ? true : false
                                }
                                let pNode = editorware.treeObj.getNode(v.folderId)
                                if (pNode) {
                                    editorware.treeObj.append(addNode, pNode)
                                    // 设置新添加子菜单为选中状态
                                    if (v.isShow) {
                                        editorware.treeObj.setChecked(addNode, true, false)
                                    }
                                    // 渲染数据
                                    v.style = JSON.parse(v.style)
                                    // console.log(v, '1111111')
                                    render(v)
                                }
                            })
                        }
                        this.centerDialogVisible = false
                    }
                })

                // return
                // if (pid && baseId) {
                //     this.$request.postForm('api/map/baseFolder/newFoldr', { folderName: file.name, pid: pid, baseId, isEditor: '1', isShow: '1', isLocked: 0 }).then(res => {
                //         if (res.code == 200) {
                //             // 添加kml文件夹
                //             let data = res.data
                //             let addData = {
                //                 name: data.folderName,
                //                 pid: data.parentFolder,
                //                 id: data.id,
                //                 type: 'folder',
                //                 isLocked: data.isLocked,
                //                 editor: data.isEditor ? true : false,
                //                 show: data.isShow ? true : false,
                //                 children: []
                //             }
                //             let node = this.$refs.treeList.getNode(pid)
                //             this.$refs.treeList.append(addData, node)
                //             this.$refs.treeList.setChecked(addData, true, false)
                //             // node.expanded = true
                //             // 添加kml数据
                //             setTimeout(() => {
                //                 let reader = new FileReader()
                //                 reader.readAsText(file, 'UTF-8')
                //                 let that = this
                //                 reader.onloadend = function(e) {
                //                     let strkml = this.result
                //                     kgUtil.toGeoJSON(strkml).then(geojson => {
                //                         geojson = that.simplifyGeoJSON(geojson)
                //                         // initMap.graphicLayer.loadGeoJSON(geojson, { flyTo: true })
                //                         console.log(geojson)
                //                         //  geojoson.features.forEach((v)=>{

                //                         //  })
                //                         // return
                //                         if (geojson.features.length > 0) {
                //                             that.createdKmlData(geojson.features, 0, geojson.features.length, data)
                //                             return
                //                             geojoson.features.forEach(v => {
                //                                 // console.log(v.geometry.type, v.geometry.type.includes('LineString'))
                //                                 if (v.geometry.type.includes('LineString') || v.geometry.type.includes('Polygon')) {
                //                                     let styles = plane
                //                                     var dataType = '',
                //                                         dataOpacity = 1
                //                                     if (v.geometry.type.includes('LineString')) {
                //                                         dataType = 'polyline'
                //                                         dataOpacity = 1
                //                                     } else if (v.geometry.type.includes('Polygon')) {
                //                                         dataType = 'polygon'
                //                                         dataOpacity = 0.5
                //                                     }
                //                                     // if (v.geometry.type.toLowerCase() == 'point') {
                //                                     //     styles = marker
                //                                     // } else if (v.geometry.type.toLowerCase() == 'polygon') {
                //                                     //     styles = plane
                //                                     // }
                //                                     styles.color = v.properties.stroke
                //                                     styles.outlineColor = v.properties.stroke
                //                                     styles.clampToGround = true
                //                                     styles.opacity = dataOpacity
                //                                     // console.log(styles)
                //                                     let datas = {
                //                                         attr: {},
                //                                         id: '',
                //                                         pid: data.id,
                //                                         name: v.properties.name ? v.properties.name : `${dataType}#${v.geometry.coordinates[0].length}`,
                //                                         positions: v.geometry.coordinates[0],
                //                                         style: styles,
                //                                         type: dataType
                //                                     }
                //                                     // render(data)
                //                                     // return
                //                                     that.$request.postForm('/api/map/draw/addDrawingBinding', { drawQueryString: JSON.stringify(datas) }).then(resData => {
                //                                         if (resData.code == 200) {
                //                                             let data = resData.data
                //                                             let addNode = {
                //                                                 name: data.name,
                //                                                 pid: data.folderId,
                //                                                 id: data.id,
                //                                                 type: data.type,
                //                                                 editor: true,
                //                                                 show: true
                //                                             }
                //                                             let pNode = editorware.treeObj.getNode(data.folderId)
                //                                             if (pNode) {
                //                                                 editorware.treeObj.append(addNode, pNode)
                //                                                 // 设置新添加子菜单为选中状态
                //                                                 editorware.treeObj.setChecked(addNode, true, false)
                //                                                 // 渲染数据
                //                                                 data.style = JSON.parse(data.style)
                //                                                 render(data)
                //                                             }
                //                                         }
                //                                     })
                //                                 }
                //                             })
                //                         }
                //                     })
                //                 }
                //             }, 100)
                //         }
                //     })
                // }
            }
        },
        // 上传图新KML
        uploadTuXinKML(e) {
            const file = e.file
            if (!file.name.includes('.kml')) {
                this.$alert('文件格式错误')
            } else {
                let baseId = sessionStorage.getItem('baseId')
                let pid = editorware.drawingId
                if (pid && baseId) {
                    this.$request.postForm('api/map/baseFolder/newFoldr', { folderName: file.name, pid: pid, baseId, isEditor: '1', isShow: '1', isLocked: 0 }).then(res => {
                        if (res.code == 200) {
                            // 添加kml文件夹
                            let data = res.data
                            let addData = {
                                name: data.folderName,
                                pid: data.parentFolder,
                                id: data.id,
                                type: 'folder',
                                isLocked: data.isLocked,
                                editor: data.isEditor ? true : false,
                                show: data.isShow ? true : false,
                                children: []
                            }
                            let node = this.$refs.treeList.getNode(pid)
                            this.$refs.treeList.append(addData, node)
                            this.$refs.treeList.setChecked(addData, true, false)
                            // node.expanded = true
                            // 添加kml数据
                            setTimeout(() => {
                                let reader = new FileReader()
                                reader.readAsText(file, 'UTF-8')
                                let that = this
                                reader.onloadend = function(e) {
                                    let strkml = this.result
                                    kgUtil.toGeoJSON(strkml).then(geojson => {
                                        geojson = that.simplifyGeoJSON(geojson)
                                        // initMap.graphicLayer.loadGeoJSON(geojson, { flyTo: true })
                                        console.log(geojson)
                                        //  geojoson.features.forEach((v)=>{

                                        //  })
                                        // return
                                        if (geojson.features.length > 0) {
                                            that.createdKmlData(geojson.features, 0, geojson.features.length, data)
                                            that.centerDialogVisible = false
                                            // return
                                            // geojoson.features.forEach(v => {
                                            //     // console.log(v.geometry.type, v.geometry.type.includes('LineString'))
                                            //     if (v.geometry.type.includes('LineString') || v.geometry.type.includes('Polygon')) {
                                            //         let styles = plane
                                            //         var dataType = '',
                                            //             dataOpacity = 1
                                            //         if (v.geometry.type.includes('LineString')) {
                                            //             dataType = 'polyline'
                                            //             dataOpacity = 1
                                            //         } else if (v.geometry.type.includes('Polygon')) {
                                            //             dataType = 'polygon'
                                            //             dataOpacity = 0.5
                                            //         }
                                            //         // if (v.geometry.type.toLowerCase() == 'point') {
                                            //         //     styles = marker
                                            //         // } else if (v.geometry.type.toLowerCase() == 'polygon') {
                                            //         //     styles = plane
                                            //         // }
                                            //         styles.color = v.properties.stroke
                                            //         styles.outlineColor = v.properties.stroke
                                            //         styles.clampToGround = true
                                            //         styles.opacity = dataOpacity
                                            //         // console.log(styles)
                                            //         let datas = {
                                            //             attr: {},
                                            //             id: '',
                                            //             pid: data.id,
                                            //             name: v.properties.name ? v.properties.name : `${dataType}#${v.geometry.coordinates[0].length}`,
                                            //             positions: v.geometry.coordinates[0],
                                            //             style: styles,
                                            //             type: dataType
                                            //         }
                                            //         // render(data)
                                            //         // return
                                            //         that.$request.postForm('/api/map/draw/addDrawingBinding', { drawQueryString: JSON.stringify(datas) }).then(resData => {
                                            //             if (resData.code == 200) {
                                            //                 let data = resData.data
                                            //                 let addNode = {
                                            //                     name: data.name,
                                            //                     pid: data.folderId,
                                            //                     id: data.id,
                                            //                     type: data.type,
                                            //                     editor: true,
                                            //                     show: true
                                            //                 }
                                            //                 let pNode = editorware.treeObj.getNode(data.folderId)
                                            //                 if (pNode) {
                                            //                     editorware.treeObj.append(addNode, pNode)
                                            //                     // 设置新添加子菜单为选中状态
                                            //                     editorware.treeObj.setChecked(addNode, true, false)
                                            //                     // 渲染数据
                                            //                     data.style = JSON.parse(data.style)
                                            //                     render(data)
                                            //                 }
                                            //             }
                                            //         })
                                            //     }
                                            // })
                                        }
                                    })
                                }
                            }, 100)
                        }
                    })
                }
            }
        },
        // 创建kml文件数据
        createdKmlData(list, index, length, foldr) {
            if (index >= length) return
            // console.log(index, length)
            let kmlData = list[index]
            // console.log(kmlData, index)
            if (kmlData.geometry.type.includes('LineString') || kmlData.geometry.type.includes('Polygon')) {
                let styles = plane

                let dataType = ''
                let dataOpacity = 1
                if (kmlData.geometry.type.includes('LineString')) {
                    dataType = 'polyline'
                    dataOpacity = 1
                } else if (kmlData.geometry.type.includes('Polygon')) {
                    dataType = 'polygon'
                    dataOpacity = 0.5
                }
                styles.color = kmlData.properties.stroke
                styles.outlineColor = kmlData.properties.stroke
                styles.clampToGround = true
                styles.opacity = dataOpacity
                let datas = {
                    attr: {},
                    id: '',
                    pid: foldr.id,
                    name: kmlData.properties.name ? kmlData.properties.name : `${dataType}#${kmlData.geometry.coordinates[0].length}`,
                    positions: kmlData.geometry.coordinates,
                    style: styles,
                    type: dataType
                }
                this.$request.postForm('/api/map/draw/addDrawingBinding', { drawQueryString: JSON.stringify(datas) }).then(resData => {
                    if (resData.code == 200) {
                        let data = resData.data
                        let addNode = {
                            name: data.name,
                            pid: data.folderId,
                            id: data.id,
                            type: data.type,
                            editor: true,
                            show: true
                        }
                        let pNode = editorware.treeObj.getNode(data.folderId)
                        if (pNode) {
                            editorware.treeObj.append(addNode, pNode)
                            // 设置新添加子菜单为选中状态
                            editorware.treeObj.setChecked(addNode, true, false)
                            // 渲染数据
                            data.style = JSON.parse(data.style)
                            // console.log(data)
                            render(data)
                            index += 1
                            setTimeout(() => {
                                this.createdKmlData(list, index, length, foldr)
                            }, 100)
                        }
                    }
                })
            } else {
                index += 1
                setTimeout(() => {
                    this.createdKmlData(list, index, length, foldr)
                }, 100)
            }
        },
        //简化geojson的坐标
        simplifyGeoJSON(geojson) {
            try {
                geojson = turf.simplify(geojson, { tolerance: 0.000001, highQuality: true, mutate: true })
            } catch (e) {
                //
            }
            return geojson
        },
        // 移动对话框
        mousedown(e) {
            mousedown(e, 'coverage', 'left')
        },
        mouseup() {
            mouseup()
        },
        renderContent(h, { node, data }) {
            if (data.type && data.type == 'folder') {
                return (
                    <div class="custom-tree-node">
                        <i class="el-icon-folder-opened icon-folder-open treeNodeIcons"></i>
                        <span class="el-tree-node__label">{node.label}</span>
                    </div>
                )
            } else {
                let className = 'el-icon-tickets treeNodeIcons'
                let titleName = ''
                // 动态设置类样式
                /**
                 *  else if (data.type && data.type == 'polyline') {
                    className = 'fa fa-yahoo'
                    titleName = '线'
                }
                 */
                if (data.type && data.type == 'billboard') {
                    className = 'fa fa-map-pin'
                    titleName = '图标点'
                } else if (data.type && data.type == 'box') {
                    className = 'fa fa-cube'
                    titleName = '长方体'
                } else if ((data.type && data.type == 'curve') || data.type == 'polyline') {
                    // 线或曲线
                    className = 'fa fa-lastfm'
                    titleName = '曲线'
                } else if (data.type && data.type == 'circle') {
                    className = 'fa fa-circle-o'
                    titleName = '圆'
                } else if (data.type && data.type == 'rectangle') {
                    className = 'fa fa-square-o'
                    titleName = '矩形'
                } else if (data.type && data.type == 'polygon') {
                    className = 'fa fa-connectdevelop'
                    titleName = '面'
                } else if (data.type && data.type == 'ellipse') {
                    className = 'fa fa-database'
                    titleName = '椭圆柱体'
                } else if (data.type && data.type == 'kml') {
                    className = 'fa fa-paper-plane'
                    titleName = 'kml'
                }

                return (
                    <div class="custom-tree-node node-icon" title={titleName}>
                        <i class={['treeNodeIcons', className]}></i>
                        <span class="el-tree-node__label">{node.label}</span>
                    </div>
                )
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.coverage {
    position: fixed;
    width: 260px;
    height: calc(100vh - 70px);
    min-height: 130px;
    top: 48px;
    left: 10px;
    z-index: 1000;
    background: rgba(30, 36, 50, 0.6);
    border-color: rgba(32, 160, 255, 0.3);
    border: 1px solid;
    border-radius: 2px;

    .coverageTitle {
        width: 100%;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid rgba(32, 160, 255, 0.3);
        display: flex;
        justify-content: space-between;
        padding: 0 15px 0 10px;
        align-items: center;
        cursor: move;
        .coverageTitleName {
            color: #ffffff;
            font-size: 12px;
            .btnsImages {
                width: 13px;
                height: 13px;
                vertical-align: middle;
            }
        }
        .closeIcon {
            cursor: pointer;
            color: #ffffff;
            font-size: 13px;
        }
    }
    .toolBox {
        width: 100%;
        height: 36px;
        border-bottom: 1px solid rgba(32, 160, 255, 0.3);
        color: #ffffff;
        display: flex;
        justify-content: flex-start;
        padding: 3px 10px;
        .halfSeparate {
            width: 1px;
            height: 20px;
            margin-top: 5px;
            background: #ffffff;
            margin-right: 10px;
        }
        .toolBtn {
            margin-right: 10px;
            &:last-child {
                margin-right: 0;
            }
            i {
                width: 28px;
                height: 28px;
                line-height: 25px;
                text-align: center;
                background-color: rgba(63, 72, 84, 0.6);
                border: #dedede 1px solid;
                cursor: pointer;
            }
        }
    }
    .treeBox {
        padding: 2px;
        width: 100%;
        height: calc(100% - 76px);
        overflow: hidden;
        .treeBoxDiv {
            width: 100%;
            height: 100%;
            .el-scrollbar {
                width: 100%;
                height: 100%;
            }
            .custom-tree-node {
                color: #ffffff;
            }
        }
    }
    .uploadProgress {
        position: fixed;
        width: 100%;
        height: 100%;
        background: rgba($color: #3f4854, $alpha: 0.7);
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 999999;
        .el-progress--circle {
            position: relative;
            left: 50%;
            top: 25%;
            transform: translateY(-50%) !important;
            transform: translateX(-50%) !important;
        }
        .uploadProgressTip {
            text-align: center;
            color: #ffffff;
            top: 30%;
            position: relative;
        }
    }
}
.uploadKMLBoxCont {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    .uploadImages {
        width: 100px;
        height: 100px;
    }
    .uploadIcon {
        color: #ffffff;
        margin-bottom: 10px;
        font-size: 64px;
    }
    .uploadfloderBox {
        text-align: center;
        position: relative;
        .uploadfloderBoxInput {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
    }
}
.zxyuploadscheduletip {
    position: fixed;
    background: rgba(0, 0, 0, 0.3);
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 2001;
    display: flex;
    justify-content: center;
    align-items: center;
    .zxyuploadscheduletipCenter {
        background: rgba(30, 36, 50, 0.6);
        // border-color: rgba(32, 160, 255, 0.3);
        display: inline-block;
        width: 420px;
        padding-bottom: 10px;
        vertical-align: middle;
        border-radius: 4px;
        border: 1px solid rgba(32, 160, 255, 0.3);
        font-size: 18px;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        text-align: left;
        overflow: hidden;
        backface-visibility: hidden;
        color: #ffffff;
        padding: 20px;
        font-size: 14px;
        line-height: 30px;
        i {
            margin-right: 10px;
        }
    }
}
</style>
<style>
.el-tree {
    background: none;
}
.el-progress__text {
    color: #ffffff !important;
}
.el-checkbox__inner {
    background: none;
}
.el-checkbox__input.is-checked .el-checkbox__inner {
    border-color: #ffffff;
}
.el-tree-node__content:hover {
    background: rgba(32, 160, 255, 0.3);
}
.el-tree-node__label {
    color: #ffffff;
    font-size: 12px;
}
.treeList .treeNodeIcons {
    color: #ffffff;
    margin-right: 5px;
}
.treeList .faImage {
    width: 14px;
    height: 14px;
    vertical-align: middle;
}
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content,
.el-tree-node:focus > .el-tree-node__content {
    background: rgba(32, 160, 255, 0.5);
}
.uploadKMLBox i.el-dialog__close {
    color: #ffffff;
}
.loadingMaskClass .el-loading-text {
    color: #ffffff;
}
.loadingMaskClass .el-loading-spinner .path {
    stroke: #ffffff;
}
.zxyuploadscheduletip .el-message-box__title {
    color: #ffffff;
    font-size: 14px;
}
</style>
